﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WorkStation.Frameworks.EasyBus.MessageQueue;
using WorkStation.Frameworks.EasyBus.Pipeline;
using WorkStation.Frameworks.EasyBus.Pipeline.Filters;
using WorkStation.Frameworks.EasyBus.Pipeline.Handles;

namespace WorkStation.Frameworks.EasyBus.Handles
{
    /// <summary>
    /// 处理消息基类
    /// </summary>
    public abstract class ProcessHandle : Handle
    {
        public IMessageListener Listener { get; set; }

        public ProcessHandle(string name = null, IFilter filter = null, int order = -1) { }

        protected override HandleResult InnerExecute(ActionContext context)
        {
            Message msg = context.Input as Message;

            IBusDataManager manager = (context as BusActionContext).Bus as IBusDataManager;

            try
            {
                return this.ProcessContent(context as BusActionContext) as HandleResult;
            }
            catch (Exception ce) 
            {
                return new ProcessFailResult(context.Input, this, this.Listener.Endpoint, ce.ToString(), ce);
            }
        }

        protected abstract IProcessHandleResult ProcessContent(BusActionContext context);    
    }

    /// <summary>
    /// 标记接口
    /// </summary>
    public interface IProcessHandleResult 
    {
        IEndpoint Endpoint { get; set; }
    }

    public class ProcessSuccessResult : SuccessHandleResult, IProcessHandleResult 
    {
        public IEndpoint Endpoint { get; set; }

        public ProcessSuccessResult(object input, IHandle handle, IEndpoint endpoint, string message = null) : base(input, handle, message) 
        {
            this.Endpoint = endpoint;
        }
    }

    public class ProcessFailResult : FailHandleResult, IProcessHandleResult
    {
        public IEndpoint Endpoint { get; set; }

        public ProcessFailResult(object input, IHandle handle, IEndpoint endpoint, string errorMessage = null, Exception exception = null) : base(input, handle, errorMessage, exception) 
        {
            this.Endpoint = endpoint;
        }
    }
}
